define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

  var Controller = {
    index: () => {
      const {reactive, onMounted} = Vue
      const {ElMessageBox} = ElementPlus
      const index = {
        setup() {
          const state = reactive({
            data: [],
            order: 'desc',
            sort: 'id',
            filter: {
              drawer: false,
              data: {
                status: 'all',
                keyword: {field: 'id', value: ''},
                category_ids: [],
                activity_type: '',
                price: {min: '', max: ''},
                sales: {min: '', max: ''},
              },
              tools: {
                keyword: {
                  type: 'tinputprepend',
                  label: '商品信息',
                  placeholder: '请输入查询内容',
                  value: {
                    field: 'id',
                    value: '',
                  },
                  options: {
                    data: [{
                      label: '商品ID',
                      value: 'id',
                    },
                      {
                        label: '商品名称',
                        value: 'title',
                      }
                      ],
                  }
                },
                category_ids: {
                  type: 'tcascader',
                  label: '商品分类',
                  value: [],
                  options: {
                    data: [],
                    props: {
                      children: 'children',
                      label: 'name',
                      value: 'id',
                      checkStrictly: true,
                      emitPath: false,
                      multiple: true,
                    },
                  },
                },
              },
              condition: {},
            },
            statusData: {
              type: {
                up: 'success',
                down: 'danger',
                hidden: 'info',
              },
              color: {
                up: 'var(--el-color-success)',
                down: 'var(--el-color-danger)',
                hidden: 'var(--el-color-info)',
              }
            },
          })

          const type = reactive({
            data: []
          })

          function getTypeData() {
            Fast.api.ajax({
              url: 'product/goods/getType',
              type: 'GET',
            }, function (ret, res) {
              type.data = res.data
              // for (key in state.filter.tools) {
              //     if (key == 'activity_type') {
              //         state.filter.tools[key].options.data = res.data[key]
              //     }
              // }
              return false
            }, function (ret, res) {
            })
          }

          function getCategorySelect() {
            Fast.api.ajax({
                url: 'product/category/select',
                type: 'GET',
            }, function (ret, res) {
                for (key in state.filter.tools) {
                    if (key == 'category_ids') {
                        state.filter.tools[key].options.data = res.data
                    }
                }
                return false
            }, function (ret, res) { })
          }

          function getData() {
            let tempSearch = JSON.parse(JSON.stringify(state.filter.data));
            for (key in tempSearch) {
              if (key == 'price' || key == 'sales') {
                if (Number(tempSearch[key].min) && Number(tempSearch[key].max)) {
                  tempSearch[key] = `${tempSearch[key].min} - ${tempSearch[key].max}`
                }
              }
            }
            let search = composeFilter(tempSearch, {
              title: 'like',
              goods_desc: 'like',
              category_ids: {
                  spacer: ',',
              },
              price: 'between',
              sales: 'between',
            });
            Fast.api.ajax({
              url: 'product/goods/index',
              type: 'GET',
              data: {
                page: pagination.page,
                list_rows: pagination.list_rows,
                order: state.order,
                sort: state.sort,
                ...search,
              },
            }, function (ret, res) {
              state.data = res.data.data;
              // console.log(state.filter.data);
              pagination.total = res.data.total
              return false;
            }, function (ret, res) {

            });
          }

          function onChangeSort({prop, order}) {
            state.order = order == 'ascending' ? 'asc' : 'desc';
            state.sort = prop;
            getData();
          }

          function onOpenFilter() {
            state.filter.drawer = true
          }

          function onChangeFilter() {
            pagination.page = 1
            getData()
            state.filter.drawer && (state.filter.drawer = false);
          }

          function onChangeTab() {
            pagination.page = 1
            getData()
          }

          const pagination = reactive({
            page: 1,
            list_rows: 10,
            total: 0,
          })

          const batchHandle = reactive({
            data: [],
          })

          function onChangeSelection(val) {
            batchHandle.data = val
          }

          function onBatchHandle(type) {
            let ids = []
            batchHandle.data.forEach((item) => {
              ids.push(item.id)
            })
            switch (type) {
              case 'delete':
                ElMessageBox.confirm('此操作将删除, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }).then(() => {
                  onDelete(ids.join(','))
                });
                break;
              default:
                onCommand({id: ids.join(','), type: type})
                break;
            }
          }

          function onCommand(item) {
            Fast.api.ajax({
              url: `product/goods/edit/id/${item.id}`,
              type: 'POST',
              data: {
                status: item.type
              }
            }, function (ret, res) {
              getData()
            }, function (ret, res) {
            })
          }

          // function onSkuCommand(item) {
          //   Fast.api.ajax({
          //     url: `shopro/goods/sku_price/edit/id/${item.id}`,
          //     type: 'POST',
          //     data: {
          //       status: item.type
          //     }
          //   }, function (ret, res) {
          //     getSkuPrice(item.goods_id);
          //   }, function (ret, res) {
          //   })
          // }

          const expandRowKeys = reactive([]);

          function onExpand(id) {
            skuPrice.data = [];
            if (expandRowKeys.includes(id)) {
              expandRowKeys.length = 0;
            } else {
              expandRowKeys.length = 0;
              expandRowKeys.push(id);
              getSkuPrice(id);
            }
          }

          const skuPrice = reactive({
            data: []
          })

          function getSkuPrice(id) {
            Fast.api.ajax({
              url: `shopro/goods/sku_price?goods_id=${id}`,
              type: 'GET',
            }, function (ret, res) {
              skuPrice.data = res.data;
              return false
            }, function (ret, res) {
            })
          }

          function onAdd() {
            Fast.api.open("product/goods/add?type=add", "添加", {
              callback() {
                getData()
              }
            })
          }

          function onEdit(id) {
            Fast.api.open(`product/goods/edit?type=edit&id=${id}`, "编辑", {
              callback() {
                getData()
              }
            })
          }

          function onDelete(id) {
            Fast.api.ajax({
              url: `product/goods/delete/id/${id}`,
              type: 'DELETE',
            }, function (ret, res) {
              getData()
            }, function (ret, res) {
            })
          }
          function onSetHot(id,hot) {
            var is_hot = hot>0 ? 0 :1;
            Fast.api.ajax({
              url: `product/goods/edit?id=`+id,
              type: 'POST',
              data: {
                "is_hot":is_hot
              }
            }, function (ret, res) {
              getData()
            }, function (ret, res) { })
          }
          function onSetTechnology(id,hot) {
            var is_hot = hot>0 ? 0 :1;
            Fast.api.ajax({
              url: `product/goods/edit?id=`+id,
              type: 'POST',
              data: {
                "is_technology":is_hot
              }
            }, function (ret, res) {
              getData()
            }, function (ret, res) { })
          }

          onMounted(() => {
            getTypeData()
            getCategorySelect()
            getData()
          })

          return {
            state,
            type,
            getData,
            onChangeSort,
            onOpenFilter,
            onChangeFilter,
            onChangeTab,
            pagination,
            batchHandle,
            onChangeSelection,
            onBatchHandle,
            onCommand,
            // onSkuCommand,
            expandRowKeys,
            onExpand,
            // skuPrice,
            getSkuPrice,
            // onOpenActivityDetail,
            // onEditStock,
            onAdd,
            onEdit,
            // onCopy,
            onDelete,
            onSetHot,
            onSetTechnology
            // onRecyclebin
          }
        }
      }
      createApp('index', index);
    },
    add: () => {

      Controller.form();
    },
    edit: () => {
      Controller.form();
    },
    form: () => {
      const {ref, reactive, onBeforeMount, onMounted, getCurrentInstance, watch, nextTick} = Vue
      const addEdit = {
        setup() {
          const {proxy} = getCurrentInstance();
          const state = reactive({
            type: new URLSearchParams(location.search).get('type'),
            id: new URLSearchParams(location.search).get('id'),
            activeStep: 0,
            tempData: {
              // isStockWarning: false,
            }
          });

          const form = reactive({
            model: {
              // type: 'normal', // 商品类型
              image: '',
              images: [],
              title: '',
              goods_desc: '',
              category_ids: '',
              weigh: 0,
              is_hot: 0,
              status: 'up',
              price: '',
              virtually_nums: '',
              params: [],
              content: '',
              tabPosition:"left"
            },
            rules: {
              image: [{required: true, message: '请选择商品主图', trigger: 'blur'}],
              // images: [{ required: true, message: '请选择轮播图', trigger: 'blur' }],
              title: [{required: true, message: '请输入商品标题', trigger: 'blur'}],
              category_ids: [{required: true, message: '请输入商品分类', trigger: 'blur'}],
              price: [{required: true, message: '请输入售卖价格', trigger: 'blur'}],
            },
          });

          //form结束

          function getDetail() {
            Fast.api.ajax({
              url: `product/goods/detail/id/${state.id}`,
              type: 'GET',
            }, function (ret, res) {
              form.model = res.data;
              form.model.images = JSON.parse(res.data.images);
              getCategorySelect();
              // 商品分类
              initCategoryIds();

              // 富文本
              Controller.api.bindevent();
              $('#goodsContent').html(form.model.content);

              return false
            }, function (ret, res) {
            })
          }


          var categoryRef = {};
          const setCategoryRef = (el, tab) => {
            if (el) {
               var zuheKey = `${tab.id}-${tab.name}`;
                  categoryRef[zuheKey] =el;
            }
          };
          const tempCategory = reactive({
            tabActive: '',
            idsArr: {},
            label: {}
          });

          function initCategoryIds() {
            tempCategory.idsArr = {}
            form.model.category_ids_arr.forEach(item => {
              if (tempCategory.idsArr[item[0]]) {
                tempCategory.idsArr[item[0]].push(item.pop())
              } else {
                tempCategory.idsArr[item[0]] = []
                tempCategory.idsArr[item[0]].push(item.pop())
              }
            })
            onChangeCategoryIds()
          }

          function onChangeCategoryIds() {
            // console.log('select',category.select);
            // categoryRef= Object.assign(categoryRef, temObject);
            nextTick(() => {
              tempCategory.label = {}
              // for (var key in categoryRef) {
              //   let keyArr = key.split('-');
              //   if (categoryRef[key].checkedNodes.length > 0) {
              //     categoryRef[key].checkedNodes.forEach((row) => {
              //       tempCategory.label[row.value] = keyArr[1] + '/' + row.pathLabels.join('/');
              //     });
              //   }
              // }


              for (var key in categoryRef) {
                let keyArr = key.split('-');
                if (categoryRef[key].checkedNodes.length > 0) {
                  categoryRef[key].checkedNodes.forEach((row) => {
                    tempCategory.label[row.value] = keyArr[1] + '/' + row.pathLabels.join('/');
                  });
                }
              }
            })
          }

          function onDeleteCategoryIds(id) {
            delete tempCategory.label[id];
            let idx = -1
            for (var key in tempCategory.idsArr) {
              tempCategory.idsArr[key].forEach((item, index) => {
                if (item == id) {
                  idx = index
                }
              })
              if (idx != -1) {
                tempCategory.idsArr[key].splice(idx, 1)
                idx = -1
              }
            }
          }

          function onClearCategoryIds() {
            tempCategory.idsArr = {}
            tempCategory.label = {}
          }

          var category = reactive({
            select: []
          });

          function getCategorySelect() {
            Fast.api.ajax({
              url: 'product/category/select',
              type: 'GET',
            }, function (ret, res) {
              category.select = res.data;
              // console.log(category.select);
              // 分类选项卡赋值
              if (res.data.length > 0) {
                tempCategory.tabActive = res.data[0].id + ''
              }
              return false
            }, function (ret, res) {
            })
          }


          function onBack() {
            state.activeStep--;
          }

          function onNext() {
            // proxy.$refs['formRef'].validate((valid) => {
            //     if (valid) {
            state.activeStep++;
            //     } else {
            //         return false;
            //     }
            // });
          }

          const validateData = ref({
            0: 0,
            1: 0,
            2: 0
          })

          function isValidate() {
            nextTick(async () => {
              for (var key in validateData.value) {
                await proxy.$refs[`formRef${key}`].validate((valid) => {
                  if (valid) {
                    validateData.value[key] = 0;
                  } else {
                    validateData.value[key] = 1;
                  }
                });
              }
            })
          }

          const isEditInit = ref(false);
          const paramsRules = {
            title: [{required: true, message: '请输入名称', trigger: 'blur'}],
            content: [{required: true, message: '请输入内容', trigger: 'blur'}],
          };

          function onSuccess(data) {
            form.model.image_wh = {
              w: data.image_width,
              h: data.image_height,
            };
          }

          function onConfirm() {
            isValidate()
            setTimeout(() => {
              if (validateData.value[0] == 0 && validateData.value[1] == 0 && validateData.value[2] == 0) {
                let submitForm = JSON.parse(JSON.stringify(form.model));

                let idsArr = [];
                for (var key in tempCategory.idsArr) {
                  idsArr.push(...tempCategory.idsArr[key]);
                }
                submitForm.category_ids = idsArr.join(',');
                submitForm.content = $("#goodsContent").val();
                console.log(submitForm);
                Fast.api.ajax({
                  url: state.type == 'add' ? 'product/goods/add' : `product/goods/edit/id/${state.id}`,
                  type: 'POST',
                  data: submitForm
                }, function (ret, res) {
                  Fast.api.close()
                }, function (ret, res) {
                })
              }
            }, 500)

          }

          onBeforeMount(() => {

            // getServiceSelect()
            if (state.type == 'edit') {
              getDetail();
              nextTick(() => {
                Controller.api.bindevent();
                $('#goodsContent').html(form.model.content);
              })
            }else{
              getCategorySelect();
              //尼玛太重要了---啥几把玩意----不整真不出来富文本编辑器
              nextTick(() => {
                Controller.api.bindevent();
              });

              // Controller.api.bindevent();
            }
          });
          return {
            state,
            form,
            categoryRef,
            setCategoryRef,
            tempCategory,
            onChangeCategoryIds,
            onDeleteCategoryIds,
            onClearCategoryIds,
            category,
            onBack,
            onNext,
            validateData,
            isValidate,
            isEditInit,
            onSuccess,
            onConfirm
          }
        }
      }
      createApp('addEdit', addEdit);
    },

    //添加结束
    select: () => {
      const {reactive, onMounted, watch, getCurrentInstance, nextTick} = Vue
      const select = {
        setup() {
          const {proxy} = getCurrentInstance();

          const state = reactive({
            data_type: new URLSearchParams(location.search).get('data_type'),
            multiple: new URLSearchParams(location.search).get('multiple') || false,
            max: new URLSearchParams(location.search).get('max') || 0,
            ids: new URLSearchParams(location.search).get('ids'), // 选中的商品ids
            goods_ids: new URLSearchParams(location.search).get('goods_ids'), // 需要搜索的商品id列表
            data: [],
            filter: {
              drawer: false,
              data: {
                category_ids: '',
                keyword: '',
                price: {
                  min: '',
                  max: '',
                },
              },
              tools: {},
            },
          })
          state.ids = state.ids ? state.ids.split(',') : []

          const category = reactive({
            id: '',
            select: [],
            detail: []
          })

          function getCategorySelect() {
            Fast.api.ajax({
              url: 'product/category/select',
              type: 'GET',
            }, function (ret, res) {
              category.select = res.data
              category.select.unshift({
                children: [],
                id: 'all',
                name: '全部分类',
              });
              if (category.select.length > 0) {
                category.id = category.select[0].id;
                getCategoryDetail();
              }
              return false
            }, function (ret, res) {
            })
          }

          function getCategoryDetail() {
            const data = category.select.find((item) => item.id == category.id);
            category.detail = data.children || [];
            state.filter.data.category_ids = data.id;
          }

          function changeCategoryIds(data) {
            state.filter.data.category_ids = data.id;
          }

          function getData() {
            let tempSearch = JSON.parse(JSON.stringify(state.filter.data));
            if (tempSearch.price.min && tempSearch.price.max) {
              tempSearch.price = `${tempSearch.price.min} - ${tempSearch.price.max}`;
            }
            // activity_type 搜索
            if (state.activity_type) {
              tempSearch.activity_type = state.activity_type;
            }
            // id 搜索
            if (state.goods_ids) {
              tempSearch.goods = {field: 'id', value: state.goods_ids};
            }
            let search = composeFilter(tempSearch, {
              keyword: 'like',
              price: 'between',
            });
            Fast.api.ajax({
              url: 'product/goods/goods/select',
              type: 'GET',
              data: {
                data_type: state.data_type,
                type: 'page',
                page: pagination.page,
                list_rows: pagination.list_rows,
                ...search,
              },
            }, function (ret, res) {
              state.data = res.data.data
              pagination.total = res.data.total

              nextTick(() => {
                state.data.forEach((l) => {
                  if (state.ids?.includes(l.id + '')) {
                    proxy.$refs['multipleTableRef']?.toggleRowSelection(l, true);
                    toggleRowSelection('row', [l], l);
                  }
                });
              });
              return false
            }, function (ret, res) {
            })
          }

          watch(() => state.filter.data, () => {
            pagination.page = 1;
            getData()
          }, {
            deep: true,
          })

          const pagination = reactive({
            page: 1,
            list_rows: 10,
            total: 0,
          })

          function onSelect(selection, row) {
            if (
              !state.max ||
              (state.max && state.max > state.ids.length)
            ) {
              if (state.ids.includes(row.id + '')) {
                let index = state.ids.findIndex((id) => id == row.id);
                state.ids.splice(index, 1);
              } else {
                state.ids.push(row.id);
              }
            }
            toggleRowSelection('row', selection, row);
          }

          function onSelectAll(selection) {
            if (
              !state.max ||
              (state.max && state.max > state.ids.length + selection.length)
            ) {
              if (selection.length == 0) {
                state.data.forEach((l) => {
                  if (state.ids.includes(l.id)) {
                    let index = state.ids.findIndex((id) => id == l.id);
                    state.ids.splice(index, 1);
                  }
                });
              } else {
                state.data.forEach((l) => {
                  if (!state.ids.includes(l.id)) {
                    state.ids.push(l.id);
                  }
                });
              }
            }
            toggleRowSelection('all', selection);
          }

          function toggleRowSelection(type, selection, row) {
            // 限制数量
            if (state.max && state.max < selection.length) {
              if (type == 'row') {
                proxy.$refs['multipleTableRef'].toggleRowSelection(row, false);
              } else if (type == 'all') {
                proxy.$refs['multipleTableRef']?.clearSelection();
                state.data.forEach((l) => {
                  if (state.ids?.includes(l.id)) {
                    proxy.$refs['multipleTableRef']?.toggleRowSelection(l, true);
                  }
                });
              }
              ElMessage({
                type: 'warning',
                message: '已到选择上限',
              });
              return false;
            }
          }

          function onSingleSelect(item) {
            Fast.api.close(item)
          }

          function onConfirm() {
            let ids = state.ids.join(',')
            Fast.api.ajax({
              url: 'shopro/goods/goods/select',
              type: 'GET',
              data: {
                type: 'select',
                search: JSON.stringify({id: [ids, 'in']})
              },
            }, function (ret, res) {
              Fast.api.close(res.data)
              return false
            }, function (ret, res) {
            })
          }

          onMounted(() => {
            getCategorySelect()
            getData()
          })

          return {
            state,
            category,
            getCategoryDetail,
            getData,
            changeCategoryIds,
            pagination,
            onSelect,
            onSelectAll,
            onSingleSelect,
            onConfirm
          }
        }
      }
      createApp('select', select);
    },

    api: {
      bindevent: function () {
        Form.api.bindevent($("form[role=form]"));
      },
    },
  };
  return Controller;
});
